﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Drawing;
using System.Data;

namespace GandA.Web.UI.Controls
{
    [
    AspNetHostingPermission(SecurityAction.Demand,
        Level = AspNetHostingPermissionLevel.Minimal),
    AspNetHostingPermission(SecurityAction.InheritanceDemand,
        Level = AspNetHostingPermissionLevel.Minimal),
    ]
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:ComboBox runat=server></{0}:ComboBox>")]
    [ToolboxBitmap(typeof(System.Web.UI.WebControls.DropDownList))]
    public class ComboBox : WebControl, IPostBackEventHandler
    {
        private EventHandler _selected_changed;
        private HiddenField _hdn_cmb;
        
        #region Propiedades
        [Bindable(true)]
        [Category("Behavior")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool AutoPostBack
        {
            get
            {
                return ViewState["_AutoPostBack"] == null ? false : (bool)ViewState["_AutoPostBack"];
            }

            set
            {
                ViewState["_AutoPostBack"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string SelectedText
        {
            get
            {
                return ViewState["_Text"] == null ? string.Empty : ViewState["_Text"].ToString();
            }

            set
            {
                ViewState["_Text"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DefaultText
        {
            get
            {
                return ViewState["_DefaultText"] == null ? string.Empty : ViewState["_DefaultText"].ToString();
            }

            set
            {
                ViewState["_DefaultText"] = value;
            }
        }

        [Bindable(true)]
        [Category("Default")]
        [DefaultValue("")]
        [Localizable(true)]
        public string SelectedValue
        {
            get
            {
                return ViewState["_SelectedValue"] == null ? string.Empty : ViewState["_SelectedValue"].ToString();
            }

            set
            {
                ViewState["_SelectedValue"] = value;
            }
        }

        //[Bindable(true)]
        //[Category("Default")]
        //[DefaultValue("")]
        //[Localizable(true)]
        //public int SelectedIndex
        //{
        //    get
        //    {
        //        EnsureChildControls();
        //        return ddlControl.SelectedIndex;
        //    }

        //    set
        //    {
        //        EnsureChildControls();
        //        ddlControl.SelectedIndex = value;
        //    }
        //}

        [Bindable(true)]
        [Category("Layout")]
        [DefaultValue("")]
        [Localizable(true)]
        public override Unit Width
        {
            get
            {
                return ViewState["_Width"] == null ? (Unit)50 : (Unit)ViewState["_Width"];
            }

            set
            {
                ViewState["_Width"] = value;
            }
        }

        //[Bindable(true)]
        [Category("Accessibility")]
        [DefaultValue("")]
        [Localizable(true)]
        public override short TabIndex
        {
            get
            {
                return ViewState["_TabIndex"] == null ? (short)1 : Convert.ToInt16(ViewState["_TabIndex"]);
            }

            set
            {
                ViewState["_TabIndex"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool EnabledValidator
        {
            get
            {
                return ViewState["_EnabledValidator"] == null ? false : (bool)ViewState["_EnabledValidator"];
            }
            set
            {
                ViewState["_EnabledValidator"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue(false)]
        [Localizable(true)]
        public bool EnabledValidatorExpression
        {
            get
            {
                return ViewState["_EnabledValidatorExpression"] == null ? false : (bool)ViewState["_EnabledValidatorExpression"];
            }
            set
            {
                ViewState["_EnabledValidatorExpression"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue("")]
        [Localizable(true)]
        public string ValidationExpression
        {
            get
            {
                return ViewState["_ValidationExpression"] == null ? string.Empty : ViewState["_ValidationExpression"].ToString();
            }
            set
            {
                ViewState["_ValidationExpression"] = value;
            }
        }

        [Bindable(true)]
        [Category("Validator")]
        [DefaultValue("")]
        [Localizable(true)]
        public string ErrorMessage
        {
            get
            {
                return ViewState["_ErrorMessage"] == null ? string.Empty : ViewState["_ErrorMessage"].ToString();
            }
            set
            {
                ViewState["_ErrorMessage"] = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DataValueField
        {
            get
            {
                return ViewState["_DataValueField"] == null ? string.Empty : ViewState["_DataValueField"].ToString();
            }
            set
            {
                ViewState["_DataValueField"] = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public string DataTextField
        {
            get
            {
                return ViewState["_DataTextField"] == null ? string.Empty : ViewState["_DataTextField"].ToString();
            }
            set
            {
                ViewState["_DataTextField"] = value;
            }
        }

        [Bindable(true)]
        [Category("Data")]
        [DefaultValue("")]
        [Localizable(true)]
        public object DataSource
        {
            get
            {
                return ViewState["_DataSource"];
            }
            set
            {
                ViewState["_DataSource"] = value;
            }
        }

        #endregion

        #region Eventos
        public event EventHandler OnSelectedChanged
        {
            add { _selected_changed += value; }
            remove { _selected_changed -= value; }
        }

        protected virtual void FireSleectedChangedEvent()
        {
            if (_selected_changed != null)
            {
                //if (!string.IsNullOrEmpty(_hdn_DatePicker.Value.Replace(",", "")))
                //{
                //    int pos = 0;
                //    string[] fechas = _hdn_DatePicker.Value.Split(',');
                //    for (pos = 0; pos < fechas.Length; pos++)
                //    {
                //        string[] fecha = fechas[pos].Split('/');
                //        if (fecha.Length == 3)
                //        {
                //            this.Value = new DateTime(Convert.ToInt32(fecha[2]), Convert.ToInt32(fecha[1]), Convert.ToInt32(fecha[0]));
                //            break;
                //        }
                //    }
                //}
                if (!string.IsNullOrEmpty(_hdn_cmb.Value))
                {
                    this.SelectedValue = _hdn_cmb.Value;
                }
                _selected_changed(this, new EventArgs());
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            //writer.AddAttribute(HtmlTextWriterAttribute.Onchange, 
            //Page.ClientScript.GetPostBackEventReference(this, String.Empty));
            base.AddAttributesToRender(writer);
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            FireSleectedChangedEvent();
        }
        #endregion

        #region Metodos
        
        protected override void OnPreRender(EventArgs e)
        {
            bool linkIncluded = false;
            foreach (Control c in Page.Header.Controls)
            {
                if (c.ID == "StyleControls")
                {
                    linkIncluded = true;
                }
            }
            if (!linkIncluded)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "StyleControls";
                csslink.Attributes.Add("href",
                                       Page.ClientScript.GetWebResourceUrl(this.GetType(), "GandA.Web.UI.Controls.Controls.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            linkIncluded = false;

            foreach (Control c in Page.Header.Controls)
            {
                if (c.ID == "StyleCombo")
                {
                    linkIncluded = true;
                }
            }
            if (!linkIncluded)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.ID = "StyleCombo";
                csslink.Attributes.Add("href",
                                       Page.ClientScript.GetWebResourceUrl(this.GetType(), "GandA.Web.UI.Controls.bootstrap-select.css"));
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                Page.Header.Controls.Add(csslink);
            }

            base.OnPreRender(e);

            string resourceName = string.Empty;
        
            ClientScriptManager cs;
            if (this.Page == null)
                cs = this.Parent.Page.ClientScript;
            else
                cs = this.Page.ClientScript;

            resourceName = "GandA.Web.UI.Controls.Scripts.bootstrap-select.js";
            cs.RegisterClientScriptResource(typeof(GandA.Web.UI.Controls.ComboBox), resourceName);

            resourceName = "GandA.Web.UI.Controls.Scripts.bootstrap.min.js";
            cs.RegisterClientScriptResource(typeof(GandA.Web.UI.Controls.ComboBox), resourceName);

            resourceName = "GandA.Web.UI.Controls.ComboBox.js";
            cs.RegisterClientScriptResource(typeof(GandA.Web.UI.Controls.ComboBox), resourceName);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(_hdn_cmb.Value))
            {
                this.SelectedValue = _hdn_cmb.Value;
            }

            PostBackOptions p = new PostBackOptions(this);
            if (this.AutoPostBack)
                writer.AddAttribute(HtmlTextWriterAttribute.Onchange, Page.ClientScript.GetPostBackEventReference(p));
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID);
            writer.AddAttribute(HtmlTextWriterAttribute.Style, Width.Value <= 0 ? "width:350px" : "width:" + Width.ToString());
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID + "_cmb");
            writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID + "_cmb");
            writer.AddAttribute("title", this.DefaultText);
            writer.AddAttribute("ErrorMessage", this.ErrorMessage);
            writer.AddAttribute("data-live-search", "true");
            //writer.AddAttribute("multiple", null);
            writer.AddAttribute(HtmlTextWriterAttribute.Tabindex, this.TabIndex <= 0 ? "1" : this.TabIndex.ToString());
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "selectpicker");
            writer.AddAttribute(HtmlTextWriterAttribute.Style, "width:" + (this.Width.Value<=0?"350px":this.Width.ToString()));
            writer.AddAttribute(HtmlTextWriterAttribute.Onchange, "setValueCmbHdn(this);" + (this.EnabledValidator ? "ValidObjectCmb(this);" : "") + (this.EnabledValidatorExpression ? "ValidExpressionCmb(this, '" + this.ValidationExpression + "');" : ""));
            writer.RenderBeginTag(HtmlTextWriterTag.Select);
            writer.Write("<option value=''></option>");
            foreach (DataRow row in ((DataTable)this.DataSource).Rows)
            {
                writer.Write("<option value='" + row[this.DataValueField] + "'" + (row[this.DataValueField].ToString().Equals(this.SelectedValue)?"Selected":"") + ">" + row[this.DataTextField] + "</option>");
            }
            
            writer.RenderEndTag();
            //_hdn_cmb.RenderControl(writer);
            base.Render(writer);
            writer.RenderEndTag();
            writer.Write("<script type=\"text/javascript\">\n\r" +
                            "function " + this.ID + "_InitializeCmb(){\n\r" +
                                "$('.selectpicker').selectpicker({\n\r" +
                                "noneResultsText: 'Sin resultados:',\n\r" +
                                "noneSelectedText: 'sin'\n\r" +
                                "});\n\r" +
                            "}\n\r" +
                            this.ID + "_InitializeCmb();" +
                        "</script>");
            writer.Write("<script>Sys.WebForms.PageRequestManager.getInstance().add_endRequest(" + this.ID + "_InitializeCmb)</script>");
        }

        protected override void OnInit(EventArgs e)
        {
            _hdn_cmb = new HiddenField();
            _hdn_cmb.ID = this.ID + "_Hidden";
            this.Controls.Add(_hdn_cmb);
            base.OnInit(e);
        }

        public override void DataBind()
        {
            if (this.DataSource != null)
            {
            }

            base.DataBind();
        }
        
        #endregion
    }
}
